package com.juyu.miliao.api.controller.wx;

import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.service.AppKeyService;
import com.juyu.miliao.api.service.WxUserInfoService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


/**
 * @author xuanqicheng
 * @create 2019-26-15:41
 */
@RestController
@RequestMapping("/wx")
@Log4j2
public class WxUserInfoController {

    @Autowired
    private WxUserInfoService wxUserInfoService;

    @Autowired
    private AppKeyService appKeyService;


    /**
     * 登录(弃用)
     * @param key
     * wx_gzh_pay：公众号充值地址，
     * wx_binding_gold_coins：关注公众号领取金币
     * wx_invite_make_money 邀请好友得金币地址
     * @param response
     * @throws IOException
     */
    @GetMapping("/wxLogin/{key}")
    public void wxLogin(@PathVariable("key") String key, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Appkey appKey = appKeyService.getAppKeyByKey("wxRedirectUrl");
        String wxRedirectUrl = appKey.getValue()+"/"+key;
        String queryString = request.getQueryString();
        if(queryString != null)
            wxRedirectUrl += "?" + queryString;
        String redirectUrl = wxUserInfoService.getRedirectUrl(wxRedirectUrl);
        log.info("公众号功能***获取code***：key:"+key+"---url:"+redirectUrl);
        response.sendRedirect(redirectUrl);
    }


    @GetMapping(value = "/openId/{urlKey}")
    public void getOpenId(HttpServletRequest request, @PathVariable("urlKey") String urlKey,
                          @RequestParam String code, @RequestParam String state,
                          HttpServletResponse response)
            throws IOException {
        String openId = wxUserInfoService.getOpenId(code,state);

        Map<String,Object> map = new HashMap<>(1);

        map.put("openId",openId);

        Appkey appKey = appKeyService.getAppKeyByKey(urlKey);

        String url = appKey.getValue()+"?openId="+openId;

        String queryString = request.getQueryString();
        int startIndex = queryString.indexOf("code");
        int endIndex = queryString.indexOf("&", startIndex);
        if(endIndex == -1) {
            queryString = queryString.substring(0, startIndex);
        } else {
            queryString = queryString.substring(0, startIndex) + queryString.substring(endIndex);
        }
        url += "&" + queryString;
        log.info("公众号功能***获取openId***：urlKey:"+urlKey+"---url:"+url);
        response.sendRedirect(url);
    }

}
